<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" v-if="permission.equipmentCategory_delete" size="small" icon="el-icon-delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="qcTemplateNameForm">
        <el-input placeholder="请选择 养护检验模版" v-model="form.qcTemplateName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.qcTemplateName"
            @click="
              form.qcTemplateName = '';
              form.qcTemplateId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openQcTemplateModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, remove, addOrUpdate } from '@/api/admin/equipment-category.js';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { mapGetters } from 'vuex';
export default {
  name: 'EquipmentManageEequipmentCategory',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'EQUIPMENT_MANAGE_EQUIPMENT_CATEGORY',
      form: {},
      query: {},
      tableOption: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        tree: true,
        lazy: true, // 懒加载
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 155,
        border: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        selectable: (row, index) => {
          return row.code != 'PRINTER' && row.code != 'AGINGCAR' && row.code != 'MACHINE' && row.code != 'AI';
        },
        dialogClickModal: false,
        showDialog: false,
        columnBtn: false,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'type',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_tool_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '养护检验模版',
            prop: 'qcTemplateName',
            hide: true
          },
          {
            label: '描述',
            prop: 'remark',
            type: 'textarea',
            maxRows: 3,
            minRows: 3
          },
          {
            label: '编订人',
            prop: 'creator',
            display: false
          },
          {
            label: '编订日期',
            prop: 'createTime',
            display: false
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.equipmentCategory_add, false),
        viewBtn: this.vaildData(this.permission.equipmentCategory_view, false),
        delBtn: this.vaildData(this.permission.equipmentCategory_delete, false),
        editBtn: this.vaildData(this.permission.equipmentCategory_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    openQcTemplateModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择养护检验模版信息（双击进行选择）',
        url: '/api/mes-product/qms-inspection-template/page?status=1&type=MI',
        isPage: true,
        rowSelectionType: 'single',
        searchSpan: 8,
        searchLabelWidth: 130,
        columnDefs: [
          {
            label: '检验模板名称',
            prop: 'name',
            search: true
          },
          {
            label: '检验模板编码',
            prop: 'code',
            search: true
          },
          {
            label: '版本号',
            prop: 'revision'
          }
        ]
      };
    },

    getSelectedRows(rowData) {
      this.form.qcTemplateId = rowData.id;
      this.$set(this.form, 'qcTemplateName', rowData.name);
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    rowSave(row, done, loading) {
      addOrUpdate(row).then(
        (res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row, index, done) {
      if (row.code === 'PRINTER' || row.code === 'AGINGCAR' || row.code === 'MACHINE' || row.code === 'AI') {
        this.$message({
          type: 'warning',
          message: '当前类别不能删除！'
        });
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.overpaymentRatio-value {
  ::v-deep .el-input__inner {
    border: none;
    border-radius: inherit;
    border-bottom: 1px solid #dcdfe6 !important;
  }
}
</style>
